package com.my.jli.webapi;

import com.my.jli.Service.HomeworkService;
import com.my.jli.Service.StudentService;
import com.my.jli.entity.Homework;
import com.my.jli.entity.HomeworkAndStudent;
import com.my.jli.entity.Student;
import com.my.jli.util.FileUtil;
import com.my.jli.util.PageUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @ClassName HomeworkRestController
 * @Description
 * @Author MaYu
 * @Date 2022/4/6 19:09
 * @Version 1.0
 **/
@RestController
@RequestMapping("/webapi/homework")
public class HomeworkRestController {

    @Value("${file-save-path}")
    private String fileSavePath;

    private Logger logger = LoggerFactory.getLogger(HomeworkRestController.class);

    private HomeworkService homeworkService;
    private StudentService studentService;
    @Autowired
    public void setHomeworkService(HomeworkService homeworkService) {
        this.homeworkService = homeworkService;
    }
    @Autowired
    public void setStudentService(StudentService studentService) {
        this.studentService = studentService;
    }

    @RequestMapping("/list")
    public List<Homework> list(){
        return homeworkService.getAll();
    }

    @GetMapping("/getById")
    public Homework getById(Integer hid){
        return homeworkService.getById(hid);
    }

    /**
     * 分页获取作业信息
     * @param page 页数
     * @param size 一页的大小
     * @param tid 教师的id
     * @return 分页工具
     */
    @GetMapping("/getByPage")
    public PageUtil getByPage(@RequestParam(value = "page", defaultValue = "0") Integer page,
                              @RequestParam(value = "size", defaultValue = "5") Integer size,
                              Integer tid){
        //ding定义排序方式
        Sort sort = Sort.by(Sort.Direction.DESC, "id");
        Page<Homework> homeworkPage;

        Pageable pageable = PageRequest.of(page, size, sort);
        homeworkPage = homeworkService.getByPage(tid, pageable);

        PageUtil pageUtil = new PageUtil(homeworkPage.getContent(), homeworkPage.getTotalElements(), page);
        pageUtil.setTotalPage(size);

        return pageUtil;
    }

    @PostMapping("/saveHomework")
    public int saveHomework(Integer hid, String title, Integer tid){
        if (hid != null && StringUtils.hasText(title) && tid != null){
            Homework homework = homeworkService.getById(hid);
            if (homework != null){
                homework.setTitle(title);
                Homework saveHomework = homeworkService.saveHomework(homework);
                return saveHomework == null ? -1 : 1;
            }
        } else if (hid == null && StringUtils.hasText(title) && tid != null){
            Homework homework1 = new Homework();
            homework1.setTitle(title);
            homework1.setStartDate(new Date());
            homework1.setEndDate(new Date(new Date().getTime() + 7 * 24 * 60 * 60 * 1000));
            homework1.setTid(tid);
            Homework saveHomework = homeworkService.saveHomework(homework1);
            return saveHomework == null ? -1 : 1;
        }
        return -1;
    }

    /**
     * 获取单个作业是否完成
     * @param hid 作业id
     * @param sid 学生id
     * @return 状态码，1为完成，-1为未完成
     */
    @GetMapping("/getHomeworkStatus")
    public int getHomeworkStatus(Integer hid, Integer sid){
        HomeworkAndStudent hs = homeworkService.getHSByHidAndSid(hid, sid);
        if (hs != null){
            return 1;
        } else {
            return -1;
        }
    }

    @DeleteMapping("/deleteHomework")
    public int deleteHomework(Integer hid){
        homeworkService.deleteHomeworkById(hid);
        return 1;
    }

    @GetMapping("/getSubmitCount")
    public int getSubmitCount(Integer hid){
        return homeworkService.getSubmitCount(hid);
    }

    /**
     * 上传作业文件
     * @param file 文件
     * @return 状态码
     */
    @RequestMapping("/upload")
    public int uploadHomework(MultipartFile file, Integer hid, Integer sid){
        //查询该作业该学生的提交记录
        HomeworkAndStudent hs = homeworkService.getHSByHidAndSid(hid, sid);
        if (hs == null){//没有记录则是第一次提交
            hs = new HomeworkAndStudent();
        }
        if (file != null && file.getSize() > 0){
            //重命名文件
            String filename = file.getOriginalFilename();
            Student student = studentService.getById(sid);
            String fileNameNew = student.getNum() + "_" + student.getName() + "_" + filename;
            //生成动态文件夹
            Homework homework = homeworkService.getById(hid);
            String homeworkPath = "作业编号_" +  homework.getId();
            String filePath = fileSavePath + "/homework/" + homeworkPath;
            File file1 = new File(filePath);
            if (!file1.exists()){
                //如果路径不存在则新建
                boolean b = file1.mkdirs();
                if (!b){
                    //如果文件路径创建失败返回-1
                    return -1;
                }
            }
            File file2 = new File(filePath + "/" + fileNameNew);
            logger.info("有新文件上传：" + file2.getPath());
            try {
                file.transferTo(file2);
            } catch (IOException e) {
                e.printStackTrace();
            }

            //提交信息保存到数据库
            hs.setDate(new Date());
            hs.setHid(hid);
            hs.setSid(sid);
            hs.setFilepath("/homework/" + homeworkPath + "/" + fileNameNew);
            homeworkService.submitHomework(hs);

            return 1;
        } else {
            return -1;
        }
    }
}
